package com.atguigu.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Base64;
import java.util.Calendar;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.jdbc.support.lob.LobCreator;

import com.atguigu.dao.SimpleBaseDaoImpl;
//@Component
public abstract class OracleUtil {
//	@Autowired
//	private static SimpleBaseDaoImpl simpleBaseDaoImpl;
	private static SimpleBaseDaoImpl simpleBaseDaoImpl =  (SimpleBaseDaoImpl) ApplicationContextRegister.getApplicationContext().getBean(SimpleBaseDaoImpl.class);
	/**
	 * clob 转 String
	 * @param clob
	 * @return
	 */
	public static String getClobStr(Clob clob){
		String reString = "";       
        Reader is;
		try {
			is = clob.getCharacterStream();
			BufferedReader br = new BufferedReader(is);
				String s = br.readLine();
				StringBuffer sb = new StringBuffer();
				while (s != null){
			        // 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
					sb.append(s);
					s = br.readLine();
			}
			reString = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return reString;
	}
	
	
	
	/**
	 * 	返回 lists 本身 : 已经把clob转化为String的lists
	 * @param lists 传入含有clob对象的数据 
	 * @return
	 */
	public static  List<Map<String, Object>> ClobToString(List<Map<String, Object>>  lists ){
		for (Map<String, Object> map : lists) {
			for (Entry<String, Object> meta : map.entrySet()) {
				Object value = meta.getValue();
				if( value instanceof Clob) {
					String str = getClobStr((Clob) value);
					meta.setValue(str);	
				} 
			}
		}
		return lists;
	}
	/**
	 * 	获取表的字段名
	 * @param baseDao
	 * @param table
	 * @return
	 */
	public static  List<Map<String, Object>>  meta(SimpleBaseDaoImpl baseDao,String table) {
		String sql="select  column_name   from   user_tab_columns   where   table_name=?";
		return baseDao.queryForList(sql, new Object[] {table});
	}
	/**
	 * 获取序列
	 * @return
	 */
	public static  String getSeq() {			
		return simpleBaseDaoImpl.queryForObject("Select SEQ_STS_ID.NextVal From Dual", String.class, new String[] {});
	}
	/**
	 * 插入lob数据
	 * @param baseDao
	 * @param sql
	 * @param obj
	 * @return
	 */
	public static  int addLob(SimpleBaseDaoImpl baseDao,String sql,Object[] obj) {	
		int i=0;
		try {
			i=baseDao.getJdbcTemplate().execute( sql, new AbstractLobCreatingPreparedStatementCallback(new DefaultLobHandler()) {
				@Override
				protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException, DataAccessException {
					try {
						for (int i=0;i<obj.length;i++) {
							if(obj[i] instanceof byte[]) {
								lobCreator.setBlobAsBytes(ps, i+1,(byte[])obj[i]);
							}else if(obj[i] instanceof InputStream) {
								lobCreator.setBlobAsBinaryStream(ps, i+1,(InputStream)obj[i] ,((InputStream)obj[i]).available());
							}else {
								ps.setObject(i+1, obj[i]);
							}
						}
//						lobCreator.setClobAsString(ps, 2, content);
//						lobCreator.setBlobAsBytes(ps, paramIndex, content);					
//						lobCreator.setClobAsCharacterStream(ps, paramIndex, characterStream, contentLength);
//						lobCreator.setClobAsString(ps, paramIndex, content);
//						lobCreator.setClobAsAsciiStream(ps, paramIndex, asciiStream, contentLength);
					} catch (Exception e) {
						e.printStackTrace();
					}

				}			
			});
		} catch (Exception e) {			
			e.printStackTrace();
		}
		return i;
	}
	
	/**
	 * 获取lob数据，未完成
	 * @param baseDao
	 * @param sql
	 * @param obj
	 * @return
	 */
	public static  List<Map<String, Object>> selectLob(SimpleBaseDaoImpl baseDao,String sql,Object[] obj) {	
		List<Map<String, Object>> i=null;
		try {
			baseDao.getJdbcTemplate().query( sql, obj,new RowMapper<Map<String, Object>>() {
				@Override
				public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
					Map<String, Object> map = new HashMap<>();
					DefaultLobHandler lobHandler = new DefaultLobHandler();
					ResultSetMetaData rsmd = rs.getMetaData();
					int columnCount = rsmd.getColumnCount();
					for(int i = 1;i <= columnCount;i++) {
						Object columnValue = null;
						String columnName = rsmd.getColumnLabel(i);	
						if(rsmd.getColumnTypeName(i).equals("BLOB")) {
							byte[] attach = lobHandler.getBlobAsBytes(rs, i);
							InputStream is = lobHandler.getBlobAsBinaryStream(rs, i);
							columnValue = is;
						}else {
							columnValue = rs.getObject(columnName);							
						}
						map.put(columnName, columnValue);
					}
					map.remove("RN");
					return map;
				}
				
			});
		} catch (Exception e) {			
			e.printStackTrace();
		}
		return i;
	}
	
//	if(map.getValue() instanceof oracle.sql.TIMESTAMPLTZ) {
//		Connection connection = baseDao.getDataSource().getConnection();
//		Calendar calender = Calendar.getInstance();
//		oracle.sql.TIMESTAMPLTZ t =(oracle.sql.TIMESTAMPLTZ)map.getValue();
//		//Timestamp timestamp = t.timestampValue(connection, calender);
//		System.out.println(timestamp.getTime());
//	}
}
